//
//  HMComposeViewController.swift
//  swift-新浪微博0
//
//  Created by 赵玉忠 on 16/9/8.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class HMComposeViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        // 监听键盘弹出的通知
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(emoticonButtonClick(noti:)), name: NSNotification.Name(rawValue: HMEmoticonButtonDidSelectedNotification), object: nil)
    }
    
    @objc internal func back() {
        self.dismiss(animated: true, completion: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    // MARK: - 监听方法
    
    @objc private func send() {
        // 发送微博
        
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        
        let accessToken = HMUserAccountViewModel.sharedModel.accessToken!
        let params = [
            "access_token": accessToken,
            "status": textView.emoticonText ?? ""
        ]
        
        // 发起请求
        HMNetworkTools.sharedTools.request(method: .Post, urlString: urlString, parameters: params) { (response, error) in
            if error != nil {
                print(error)
                SVProgressHUD.showError(withStatus: "发送失败")
                return
            }
            print(response)
            SVProgressHUD.showSuccess(withStatus: "发送成功")
        }
    }

    
    @objc private func emoticonButtonClick(noti: NSNotification) {
        // 1. 取到模型
        let emoticon = noti.userInfo!["emoticon"]! as! HMEmoticon
        // 2. 打印
        textView.inserEmoticon(emoticon: emoticon)
        
//        if emoticon.type == 1 {
//            // emoji表情
//            textView.insertText((emoticon.code! as NSString).emoji())
//        }else{
//            // 图片表情添加到表情模型里面
//            // 1. 先将取到表情的图片名字初始化一个UIImage
//            // 取到表情图片所在bundle
//            let bundle = HMEmoticonKeyboardViewModel.sharedViewModel.emoticonBundel
//            let image = UIImage(named: "\(emoticon.path!)/\(emoticon.png!)", in: bundle, compatibleWith: nil)
//            
//            // 2. 将第1步生成的图片设置到一个初始化好的`文字附件(NSTextAttachment)`
//            let attachment = NSTextAttachment()
//            // 2.1 设置图片的大小
//            let imageWH = textView.font!.lineHeight
//            attachment.bounds = CGRect(x: 0, y: -4, width: imageWH, height: imageWH)
//            // 2.2 设置图片
//            attachment.image = image
//            
//            // 3. 将第2步的文字附件添加到现有的文字(富文本)中
//            let attr = NSMutableAttributedString(attributedString: textView.attributedText)
//            attr.append(NSAttributedString(attachment: attachment))
//            // 这一句代码代表设置富文本的字体大小
//            attr.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(0, attr.length))
//            
//            // 4. 将添加完成的富文本，重新赋值到textView中
//            textView.attributedText = attr
//        }
    }

    @objc private func keyboardWillChangeFrame(noti: Notification) {
        
        // 取到键盘的最终要停留的位置
        let frame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        // 取到键盘的执行动画时间
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        print("键盘的最终位置 \(frame)")
        composeToolBar.snp_updateConstraints { (make) in
            // 弹出：667 - 409.0 = 258
            // 关闭  667 - 667 = 0
            make.bottom.equalTo(self.view).offset(frame.origin.y - HMScreenH)
        }
        
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
    }
    
    // MARK: - 懒加载控件
    
    /// 标题
    internal lazy var titleLabel: UILabel = {
        let titleLabel = UILabel()
        titleLabel.numberOfLines = 0
        titleLabel.textAlignment = .center
        titleLabel.font = UIFont.systemFont(ofSize: 16)
        if let name = HMUserAccountViewModel.sharedModel.account?.name {
            let title = "发微博\n\(name)"
            // 通过 String 初始化一个富文本
            let attributedText = NSMutableAttributedString(string: title)
            // 取到昵称的范围
            let range = (title as NSString).range(of: name)
            // 设置指定范围的文字的属性
            attributedText.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 14), NSForegroundColorAttributeName: UIColor.lightGray], range: range)
            titleLabel.attributedText = attributedText
        }else {
            titleLabel.text = "发微博"
        }
        titleLabel.sizeToFit()
        return titleLabel
    }()
    
    internal lazy var rightButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: #selector(send), for: .touchUpInside)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        // 设置不同状态的按钮背景图
        button.setBackgroundImage(UIImage(named: "common_button_orange"), for: UIControlState.normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: UIControlState.highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: UIControlState.disabled)
        // 设置不同状态下的按钮文字颜色
        button.setTitleColor(UIColor.gray, for: UIControlState.disabled)
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.setTitle("发送", for: UIControlState.normal)
        // 设置按钮的大小
        button.frame.size = CGSize(width: 44, height: 30)
        
        return button
        
    }()
    
    internal lazy var textView: HMTextView = {
        let textView = HMTextView()
        textView.placeholder = "听说下雨天音乐和辣更配哟~~"
        textView.delegate = self
        textView.font = UIFont.systemFont(ofSize: 16)
        // 垂直方向总是有弹簧效果
        textView.alwaysBounceVertical = true
        // 在拖动的时候关闭键盘
        // textView.keyboardDismissMode = .onDrag
        return textView
    }()
    
    internal lazy var composeToolBar: HMComposeToolBar = {
        let toolBar = HMComposeToolBar()
        toolBar.delegate = self
        return toolBar
    }()
    
    internal lazy var pictureView: HMComposePictureView = {
        let view = HMComposePictureView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout())
        view.backgroundColor = UIColor.white
        view.addImageClosure = { [weak self] in
            print("加号按钮点击了")
            // 弹出选择图片的控制器
            self?.selectPicture()
        }
        return view
    }()
    
    
    /// 表情键盘
    internal lazy var emoticonKeyboard: HMEmotionKeyboard = {
        let v = HMEmotionKeyboard()
        v.frame.size = CGSize(width: HMScreenW, height: 216)
        return v
    }()
}


// MARK: - HMComposeToolBarDelegate
extension HMComposeViewController: HMComposeToolBarDelegate {
    /// 定义的协议方法
    internal func composeToolBar(toolBar: HMComposeToolBar, type: ComposeToolBarButtonType) {
        
        switch type {
        case .picture:
            selectPicture()
        case .mention:
            print("@")
        case .trend:
            print("#")
        case .emotion:
            print("表情")
            changeKeyboard()
        case .add:
            print("+")
        }
    }
    
    internal func selectPicture() {
        let vc = UIImagePickerController()
        // 成为代理，只有成为了代理之后才可以取到选择之后的图片
        vc.delegate = self
        // 判断前置或者后置摄像头是否可用
        // UIImagePickerController.isCameraDeviceAvailable(UIImagePickerControllerCameraDevice)
        
        // 判断某个数据类型是否可用
        //        if UIImagePickerController.isSourceTypeAvailable(.camera) == false{
        //            print("照相机不可用")
        //        }
        vc.sourceType = .photoLibrary
        // 代表是否可以编辑 --> 会在选择完图片之后，提示一个截图图片部分内容的正方形框
        // vc.allowsEditing = true
        self.present(vc, animated: true, completion: nil)
    }
    
    
    /// 如何切换键盘
    private func changeKeyboard(){
        
        // 如果textView的输入view不在存的话，---> 代表没有设置键盘，默认是系统的键盘
        // 如果inputView为nil，那么就是系统键盘
        if textView.inputView == nil {
            // 设置自定义的View为textView的输入键盘
            textView.inputView = emoticonKeyboard
        }else{
            // 当前是表情键盘，更改为系统的键盘
            textView.inputView = nil
        }
        // 重新刷新inputView
        textView.reloadInputViews()
        
        // 判断是否是第一响应者，如果不是，那么成为第一响应者，会弹起键盘
        if !textView.isFirstResponder {
            textView.becomeFirstResponder()
        }
        
        // 告诉toolBar当前是什么键盘
        composeToolBar.isSystemKeyboard = textView.inputView == nil
    }
}


// MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate
extension HMComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    // 一旦实现了代理方法，那么imagePickerController就不会自动关闭了
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        print(info)
        // 取到对应的图片
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        // 不能直接将原图添加到数组里面
        // 需要对图片进行压缩
        // 可以将图片缩放到指定的大小
        let img = image.scaleTo(width: 600)
        pictureView.addImage(image: img)
        let data = UIImagePNGRepresentation(img)!
        (data as NSData).write(toFile: "/Users/heima/Desktop/bbbb.png", atomically: true)
        picker.dismiss(animated: true, completion: nil)
    }
}


// MARK: - UITextViewDelegate
extension HMComposeViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 取消第一响应者
        // self.textView.resignFirstResponder()
        self.view.endEditing(true)
    }
}

// MARK: - 初始化界面的逻辑

extension HMComposeViewController{
    internal func setupUI() {
        self.view.backgroundColor = UIColor.white
        // 设置左边返回
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(back))
        navigationItem.titleView = titleLabel
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        // 默认设置为不可用
        navigationItem.rightBarButtonItem?.isEnabled = false
        
        view.addSubview(textView)
        view.addSubview(composeToolBar)
        textView.addSubview(pictureView)
        
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view)
        }
        
        composeToolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.left.right.equalTo(self.view)
            make.height.equalTo(44)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(100)
            make.left.equalTo(textView).offset(10)
            make.width.equalTo(textView.snp_width).offset(-20)
            make.height.equalTo(pictureView.snp_width)
        }
    }
}
